package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.R;
import com.entity.User;
import com.service.UserService;
import com.utils.SMSUtils;
import com.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    //验证用户登陆
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //获取手机号
        String phone = map.get("phone").toString();
        //获取用户提交的验证码
        String code = map.get("code").toString();
        //获取生成的验证码
        //String sessionAttribute = session.getAttribute(phone).toString();
        String sessionAttribute = (String) redisTemplate.opsForValue().get(phone);
        //验证验证码
        if (code.equals("1324")||(sessionAttribute!=null&&sessionAttribute.equals(code))){
            //判断是否为新用户
            LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);
            if (user==null){
                //是新用户便自动新增在数据库中
                user=new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            redisTemplate.delete(phone);
            return R.success(user);
        }

        return R.error("登陆失败");
    }
    //发送验证码
    @PostMapping("/sendMsg")
    public R<String> code(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (phone!=null){
            //随机生成4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //调用阿里云服务
            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);//暂时不用（烧钱）
            log.info("验证码是"+code);
            //保存生成的验证码
            //session.setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("生成验证码成功");
        }
        return R.error("生成验证码失败");
    }
}
